package com.gpjcjl.ui;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.base.lib.Logs;
import com.gpjcjl.App;
import com.gpjcjl.database.DbHelper;
import com.gpjcjl.entity.Record;
import com.gpjcjl.entity.RecordDetail;
import com.gpjcjl.entity.Result;
import com.gpjcjl.entity.SettingProfile;
import com.gpjcjl.http.HttpManager;
import com.gpjcjl.http.HttpService;
import com.gpjcjl.http.RxSchedulers;
import com.gpjcjl.http.SingleLiveEvent;
import com.gpjcjl.util.MathUtil;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.reactivex.disposables.CompositeDisposable;

/**
 * @author yinbiao
 */
public class RecordDetailViewModel extends AndroidViewModel {

    private static final String TAG = "MainViewModel";

    CompositeDisposable disposable;

    public RecordDetailViewModel(@NonNull Application application) {
        super(application);
        disposable = new CompositeDisposable();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        //页面销毁时调用
        Logs.d(TAG, "onCleared:");
        disposable.clear();
    }


    @SuppressLint("HardwareIds")
    public LiveData<Result<List<RecordDetail>>> recordDetailList(boolean isRemote, Record record) {
        MutableLiveData<Result<List<RecordDetail>>> result = new SingleLiveEvent<>();
        if (isRemote) {
            disposable.add(HttpManager.getInstance().getService(HttpService.class)
                    .recordDetailList(App.getInstance().getAndroidId(), record.getId())
                    .compose(RxSchedulers.ioMain())
                    .subscribe(bean -> {
                        result.setValue(bean);
                    }, throwable -> {
                        result.setValue(Result.error(throwable.getMessage()));
                        Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                    }));
        } else {
            System.out.println("测试：" + record.getId());
            List<RecordDetail> list = DbHelper.getInstance().getDataBase().recordDetailDao()
                    .findByRecordId(record.getId());
            result.setValue(Result.success("成功", list));
        }
        return result;
    }


    @SuppressLint("HardwareIds")
    public LiveData<Result<String>> editRecordDetail(boolean isRemote, RecordDetail detail) {
        MutableLiveData<Result<String>> result = new SingleLiveEvent<>();
        if (isRemote) {
            Map<String, String> params = new HashMap<>();
            params.put("rid", detail.getRid());
            params.put("check_num", detail.getCheck_num());
            params.put("produce", detail.getProduce());
            params.put("produce_time", detail.getProduce_time());
            params.put("num", detail.getNum());
            params.put("around", detail.getAround());
            params.put("wall", detail.getWall());
            params.put("weight", detail.getWeight());
            params.put("bottle", detail.getBottle());
            params.put("water_gage", detail.getWater_gage());
            params.put("airtight", detail.getAirtight());
            params.put("epilog", detail.getEpilog());
            params.put("scrap", detail.getScrap());
            params.put("id", detail.getId());
            disposable.add(HttpManager.getInstance().getService(HttpService.class)
                    .editRecordDetail(App.getInstance().getAndroidId(), params)
                    .compose(RxSchedulers.ioMain())
                    .subscribe(bean -> {
                        result.setValue(bean);
                    }, throwable -> {
                        result.setValue(Result.error(throwable.getMessage()));
                        Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                    }));
        } else {
            DbHelper.getInstance().getDataBase().recordDetailDao().update(detail);
            result.setValue(Result.success("保存成功"));
        }
        return result;
    }

    /**
     * 新增钢瓶信息
     *
     * @param isRemote
     * @param detail
     * @return
     */
    @SuppressLint("HardwareIds")
    public LiveData<Result<String>> insertRecordDetail(boolean isRemote, RecordDetail detail) {
        MutableLiveData<Result<String>> result = new SingleLiveEvent<>();
        if (isRemote) {
            Map<String, String> params = new HashMap<>();
            params.put("rid", detail.getRid());
            params.put("check_num", detail.getCheck_num());
            params.put("produce", detail.getProduce());
            params.put("produce_time", detail.getProduce_time());
            params.put("num", detail.getNum());
            params.put("around", detail.getAround());
            params.put("wall", detail.getWall());
            params.put("weight", detail.getWeight());
            params.put("bottle", detail.getBottle());
            params.put("water_gage", detail.getWater_gage());
            params.put("airtight", detail.getAirtight());
            params.put("epilog", detail.getEpilog());
            params.put("scrap", detail.getScrap());
            params.put("id", detail.getId());
            disposable.add(HttpManager.getInstance().getService(HttpService.class)
                    .editRecordDetail(App.getInstance().getAndroidId(), params)
                    .compose(RxSchedulers.ioMain())
                    .subscribe(bean -> {
                        result.setValue(bean);
                    }, throwable -> {
                        result.setValue(Result.error(throwable.getMessage()));
                        Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                    }));
        } else {
            DbHelper.getInstance().getDataBase().recordDetailDao().insertAll(detail);
            result.setValue(Result.success("保存成功"));
        }
        return result;
    }

    /**
     * 根据设置，生成一条钢瓶记录
     *
     * @param record
     * @param list
     * @return
     */
    public LiveData<Result<RecordDetail>> createRecordDetail(@NonNull Record record, List<RecordDetail> list) {
        MutableLiveData<Result<RecordDetail>> result = new SingleLiveEvent<>();
        String checkNum = record.getStart_num();
        if (list != null && list.size() > 0) {
            Integer lastNum = Integer.parseInt(list.get(list.size() - 1).getCheck_num()) + 1;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < checkNum.length(); i++) {
                sb.append("0");
            }
            //格式化成startNum一样的长度
            DecimalFormat decimalFormat = new DecimalFormat(sb.toString());
            checkNum = decimalFormat.format(lastNum);
        }
        RecordDetail detail = new RecordDetail();
        detail.setCheck_num(checkNum);
        //        detail.setProduce(SettingProfile.getProduce());
        detail.setProduce_time(SettingProfile.getProduceTime());
        if ("自动".equals(SettingProfile.getNumType())) {
            detail.setNum(MathUtil.get8RandomString());
        }
        detail.setAround(SettingProfile.getAround());
        detail.setWall(SettingProfile.getWall());
        detail.setWeight(SettingProfile.getWeight());
        detail.setBottle(SettingProfile.getBottle());
        detail.setWater_gage(SettingProfile.getWater_gage());
        detail.setAirtight(SettingProfile.getAirtight());
        detail.setEpilog(SettingProfile.getEpilog());
        detail.setScrap(SettingProfile.getScrap());
        detail.setId(UUID.randomUUID().toString());
        detail.setRid(record.getId());
        result.setValue(Result.success("成功", detail));
        return result;
    }

    public LiveData<Result<String>> deleteRecordDetail(boolean isRemote, RecordDetail detail) {
        MutableLiveData<Result<String>> result = new SingleLiveEvent<>();
        if (isRemote) {
            disposable.add(HttpManager.getInstance().getService(HttpService.class)
                    .delRecordDetail(App.getInstance().getAndroidId(), detail.getRid(), detail.getId())
                    .compose(RxSchedulers.ioMain())
                    .subscribe(bean -> {
                        result.setValue(bean);
                    }, throwable -> {
                        result.setValue(Result.error(throwable.getMessage()));
                        Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                    }));
        } else {
            DbHelper.getInstance().getDataBase().recordDetailDao().delete(detail);
            result.setValue(Result.success("删除成功"));
        }
        return result;
    }

    /**
     * 根据钢瓶编号模糊查询
     *
     * @param isRemote
     * @param recordId
     * @param keyword
     * @return
     */
    public LiveData<Result<List<RecordDetail>>> searchList(boolean isRemote, String recordId, String keyword) {
        MutableLiveData<Result<List<RecordDetail>>> result = new SingleLiveEvent<>();
        if (isRemote) {
            disposable.add(HttpManager.getInstance().getService(HttpService.class)
                    .searchRecordDetail(App.getInstance().getAndroidId(), recordId, keyword)
                    .compose(RxSchedulers.ioMain())
                    .subscribe(bean -> {
                        result.setValue(bean);
                    }, throwable -> {
                        result.setValue(Result.error(throwable.getMessage()));
                        Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                    }));
        } else {
            List<RecordDetail> list;
            System.out.println("测试：" + recordId);
            if (TextUtils.isEmpty(keyword)) {
                list = DbHelper.getInstance().getDataBase().recordDetailDao().findByRecordId(recordId);
            } else {
                list = DbHelper.getInstance().getDataBase().recordDetailDao().findByKeyword(recordId, keyword);
            }
            result.setValue(Result.success("搜索成功", list));
        }
        return result;
    }

    /**
     * 扫描二维码查询
     *
     * @param url
     * @return
     */
    public LiveData<Result<RecordDetail>> scan(String url) {
        MutableLiveData<Result<RecordDetail>> result = new SingleLiveEvent<>();
        disposable.add(HttpManager.getInstance().getService(HttpService.class)
                .getQCode(App.getInstance().getAndroidId(), url)
                .compose(RxSchedulers.ioMain())
                .subscribe(bean -> {
                    result.setValue(bean);
                }, throwable -> {
                    result.setValue(Result.error(throwable.getMessage()));
                    Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                }));
        return result;
    }
}
